/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 */

import React, {useEffect, useRef, useState} from 'react';
import type {PropsWithChildren} from 'react';
import {
  Button,
  Pressable,
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
} from 'react-native';

import {WebView} from 'react-native-webview';
import {
  useCameraDevice,
  Camera,
  useCameraPermission,
  useCodeScanner,
} from 'react-native-vision-camera';

import NfcManager, {NfcTech} from 'react-native-nfc-manager';
NfcManager.start();

import ReactNativeBiometrics, {
  Biometrics,
  BiometryTypes,
} from 'react-native-biometrics';

const rnBiometrics = new ReactNativeBiometrics();

function App(): React.JSX.Element {
  const webViewRef = useRef<WebView | null>(null);

  const [nfcMessage, setNfcMessage] = useState('');

  const [webViewMessage, setWebViewMessage] = useState('');

  const device = useCameraDevice('back');

  const {hasPermission, requestPermission} = useCameraPermission();

  const [barCode, setBarCode] = useState('');
  const [isActive, setIsActive] = useState(true);
  const codeScanner = useCodeScanner({
    codeTypes: ['codabar', 'qr', 'ean-13', 'code-128'],

    onCodeScanned: codes => {
      console.log('codes: ', codes);
      if (codes.length > 0) {
        // setIsActive(false);
        setBarCode(codes[0].value ?? '');
        setOpenCamera(false);
      }
      // console.log(`Scanned ${codes.length} codes!`);
    },
  });
  const [openCamera, setOpenCamera] = useState(false);
  const onCamera = async () => {
    const res = await requestPermission();
    // setIsActive(true);
    setOpenCamera(true);

    console.log('res: ', res);
  };

  /**
   * 发送消息到web view
   *
   */
  const onSendMessageToWebView = () => {
    if (webViewRef.current) {
      console.log('------------');
      webViewRef.current.postMessage(
        // JSON.stringify({
        //   event: 'send',
        //   data: 'content',
        // }),
        'message from react native' + Date.now() + '*-*',
      );
    }
  };
  const barcodeReceived = e => {
    console.log('e: ', e);
  };

  /**
   * nfc 读取
   *
   */
  async function onReadNdef() {
    try {
      console.log('read nfc');
      // register for the NFC tag with NDEF in it
      await NfcManager.requestTechnology(NfcTech.Ndef);
      console.log('NfcTech.Ndef: ', NfcTech.Ndef);
      // the resolved tag object will contain `ndefMessage` property
      const tag = await NfcManager.getTag();
      console.warn('Tag found', tag);
      setNfcMessage(JSON.stringify(tag));
    } catch (ex) {
      console.warn('Oops!', ex);
    } finally {
      // stop the nfc scanning
      NfcManager.cancelTechnologyRequest();
    }
  }

  const [sign, setSign] = useState('');
  async function onLogin() {
    console.log('指纹识别');

    let epochTimeSeconds = Math.round(new Date().getTime() / 1000).toString();
    let payload = epochTimeSeconds + 'some message';

    rnBiometrics
      .createSignature({
        promptMessage: 'Sign in',
        payload: payload,
      })
      .then(resultObject => {
        const {success, signature} = resultObject;

        if (success) {
          console.log(signature);
          setSign(signature);
          // verifySignatureWithServer(signature, payload)
        }
      });
  }

  const [publicKey, setPublicKey] = useState('');
  function onCreateKey() {
    rnBiometrics.createKeys().then(resultObject => {
      const {publicKey: key} = resultObject;
      setPublicKey(key);
      console.log('key', key);
      // sendPublicKeyToServer(publicKey);
    });
  }

  const [deleteRes, setDeleteRes] = useState('');
  function onDeleteKey() {
    rnBiometrics.deleteKeys().then(resultObject => {
      const {keysDeleted} = resultObject;

      if (keysDeleted) {
        setDeleteRes('Successful deletion');
        console.log('Successful deletion');
      } else {
        setDeleteRes(
          'Unsuccessful deletion because there were no keys to delete',
        );
        console.log(
          'Unsuccessful deletion because there were no keys to delete',
        );
      }
    });
  }

  const [exitKey, setExitKey] = useState('');
  function onExitKey() {
    rnBiometrics.biometricKeysExist().then(resultObject => {
      const {keysExist} = resultObject;

      if (keysExist) {
        console.log('Keys exist');
        setExitKey('Keys exist');
      } else {
        setExitKey('Keys do not exist or were deleted');
        console.log('Keys do not exist or were deleted');
      }
    });
  }

  const [keyType, setKeyType] = useState('');
  function onType() {
    rnBiometrics.isSensorAvailable().then(resultObject => {
      const {available, biometryType} = resultObject;
      console.log('available: ', available);
      console.log('biometryType: ', biometryType);
      if (available && biometryType === BiometryTypes.TouchID) {
        setKeyType('TouchID is supported');
        console.log('TouchID is supported');
      } else if (available && biometryType === BiometryTypes.FaceID) {
        setKeyType('FaceID is supported');
        console.log('FaceID is supported');
      } else if (available && biometryType === BiometryTypes.Biometrics) {
        setKeyType('Biometrics is supported');
        console.log('Biometrics is supported');
      } else {
        setKeyType('Biometrics not not not supported');
        console.log('Biometrics not supported');
      }
    });
  }

  function onSimple() {
    rnBiometrics
      .simplePrompt({promptMessage: 'Confirm fingerprint'})
      .then(resultObject => {
        const {success} = resultObject;

        if (success) {
          console.log('successful biometrics provided');
        } else {
          console.log('user cancelled biometric prompt');
        }
      })
      .catch(() => {
        console.log('biometrics failed');
      });
  }
  return (
    //   <NavigationContainer>
    //     <Stack.Navigator>
    //       <Stack.Screen
    //         name="Home"
    //         component={HomeScreen}
    //         options={{title: 'Welcome'}}
    //       />
    //       <Stack.Screen name="Profile" component={ProfileScreen} />
    //     </Stack.Navigator>
    //     <Text>ok</Text>
    //   </NavigationContainer>
    <SafeAreaView
      style={{
        flex: 1,
        backgroundColor: '#fff',
      }}>
      <View
        style={{
          minHeight: '100%',
        }}>
        <Button onPress={onReadNdef} title="获取nfc"></Button>
        <Text>nfc结果: {nfcMessage}</Text>
        <Button title="指纹识别支持类型" onPress={onType}></Button>
        <Text>指纹识别支持类型：{keyType}</Text>
        <Button title="指纹识别delete key" onPress={onDeleteKey}></Button>
        <Text>删除结果：{deleteRes}</Text>
        <Button title="指纹识别create key" onPress={onCreateKey}></Button>
        <Text>指纹识别create key结果：{publicKey}</Text>
        <Button title="指纹识别exit key" onPress={onExitKey}></Button>
        <Text>存在key?：{exitKey}</Text>
        <Button title="指纹识别 login" onPress={onLogin}></Button>
        <Text>登录密钥：{sign}</Text>
        <Button title="指纹识别 simple" onPress={onSimple}></Button>
        <Text>登录密钥：</Text>
        <Button title="相机扫码" onPress={onCamera}></Button>
        <Text>扫描内容：{barCode}</Text>
        <Button title="关闭相机" onPress={() => setOpenCamera(false)}></Button>
        <Text>相机权限：{hasPermission ? '正常' : '异常'}</Text>

        {device && hasPermission && openCamera ? (
          <View
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              zIndex: 999,
              height: '100%',
              width: '100%',
              backgroundColor: 'pink',
              // flex: 1,
            }}>
            <Camera
              device={device}
              isActive={true}
              codeScanner={codeScanner}
              collapsable={true}
              style={StyleSheet.absoluteFill}
              photo={true}
            />

            <Button
              title="关闭相机"
              onPress={() => setOpenCamera(false)}></Button>
          </View>
        ) : (
          <Text>相机关闭</Text>
        )}

        {/* <Button
          onPress={onSendMessageToWebView}
          title="发送消息到web view"></Button>
        <Text>web view 发送的消息： {webViewMessage}</Text>
        <WebView
          ref={webViewRef}
          originWhitelist={['*']}
          style={{
            // flex: 1,
            height: 200,
            backgroundColor: '#fff',
          }}
          onMessage={e => {
            console.log('e: ', e);
            setWebViewMessage(JSON.stringify(e.nativeEvent.data));
          }}
          source={{
            uri: `https://toollist.net/zh/bar-code`,
            // uri: '127.0.0.1:5500/public/index.html',
          }}
          onLoadEnd={() => {
            console.log('加载结束');
          }}
          onError={() => {
            console.log('加载异常');
          }}
          renderError={() => <Text>加载异常</Text>}
        /> */}
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
  },
  highlight: {
    fontWeight: '700',
  },
});

export default App;
